import os
from dataclasses import dataclass, field
from typing import Optional

# Load environment variables from project root .env if present
try:
    from dotenv import load_dotenv  # type: ignore
    _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
    load_dotenv(os.path.join(_PROJECT_ROOT, ".env"), override=False)
except Exception:
    # dotenv is optional; ignore if unavailable
    pass


@dataclass
class RedisSettings:
    host: str = field(default_factory=lambda: os.getenv("REDIS_HOST", "localhost"))
    port: int = int(os.getenv("REDIS_PORT", "6379"))
    password: Optional[str] = os.getenv("REDIS_PASSWORD")
    db: int = int(os.getenv("REDIS_DB", "0"))
    enabled: bool = os.getenv("REDIS_ENABLED", "false").lower() in ("1", "true", "yes", "on")
    # Optional TLS/SSL support, some managed Redis services use TLS ports (e.g., 16379)
    ssl: bool = os.getenv("REDIS_SSL", "false").lower() in ("1", "true", "yes", "on")


_SETTINGS: Optional[RedisSettings] = None


def get_redis_settings() -> RedisSettings:
    global _SETTINGS
    if _SETTINGS is not None:
        return _SETTINGS
    _SETTINGS = RedisSettings()
    return _SETTINGS